package com.huaboot.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.huaboot.commont.exception.BusinessException;
import com.huaboot.commont.exception.ErrorCode;
import com.huaboot.framework.redis.config.RedisCache;
import com.huaboot.framework.security.user.JwtTokenUserInfo;
import com.huaboot.framework.security.user.LoginUser;
import com.huaboot.framework.security.utils.JwtUtil;
import com.huaboot.framework.security.utils.SecurityUtil;
import com.huaboot.system.service.AuthLoginService;
import com.huaboot.system.service.SysUserTokenService;
import com.huaboot.system.vo.AuthLoginReqVO;
import com.huaboot.system.vo.AuthLoginRespVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import java.util.Objects;

/**
 * @Author ff
 * @Date 2023/8/27 1:22 下午
 * @Version 1.0
 */

@Service
public class AuthLoginServiceImpl implements AuthLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserTokenService sysUserTokenService;


    @Override
    public AuthLoginRespVO loginByAccount(AuthLoginReqVO login) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(login.getUsername(),login.getPassword());

        Authentication authenticate = null;
        try {
            authenticate = authenticationManager.authenticate(authenticationToken);
        }catch (BadCredentialsException e) {
            throw new BusinessException(ErrorCode.USER_PASSWORD_ERROR);
        }
        if(Objects.isNull(authenticate)){
            throw new BusinessException(ErrorCode.USER_PASSWORD_ERROR);
        }
        //获取登录用户对象信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //创建token
        return sysUserTokenService.createTokenUserInfo(loginUser);
    }

    @Override
    public void logout(String accessToken) {
        LoginUser loginUser = SecurityUtil.getAuthentication();

        //删除token缓存
        redisCache.deleteObject("login:"+loginUser.getUserId());
        //更改数据库中token到期时间
        sysUserTokenService.updateExpireToken(loginUser.getUserId());
    }

    @Override
    public AuthLoginRespVO getAccessToken(String refreshToken) {

        return sysUserTokenService.refreshToken(refreshToken);
    }


}
